import Taro from '@tarojs/taro';
import { create } from 'zustand';
import { immer } from 'zustand/middleware/immer';
import {
    operateDemand,
    cancelOperateDemand,
    operateCollect,
    operateCancelCollect,
} from '@/business/services/demand/demand';

import { userCollectionPage } from '@/business/services/user/userInfo';

/**
 * @description 我的收藏
 * @author Shawn
 */

type RequestFunction = (
    pageParams: PageParams,
    isAppend?: boolean,
) => Promise<void>;

type RequestFunction2 = (demandId: string, type: string, status: string) => Promise<void>;

type RequestFunction3 = (demandId: string) => Promise<void>;

type State = {
    // 我的收藏列表
    myColletList: any[];
    // 分页信息
    pageInfo: PageInfo;
    // 数据是否加载完成
    isDataLoaded: boolean;
    // 是否有更多数据
    hasMore: boolean;
};

type Actions = {
    // 获取需求列表
    getMyColletList: RequestFunction;
    // 上拉加载/下拉刷新
    handlePullUpOrDown: RequestFunction;
    // 点赞、点踩
    handleLikeOrDislike: RequestFunction2;
    // 取消点赞、点踩
    handleCancelLikeOrDislike: RequestFunction2;
    // 收藏
    handleCollect: RequestFunction2;
    // 取消收藏
    handleCancelCollect: RequestFunction3;
};

const initialState: State = {
    // 我的收藏列表
    myColletList: [],
    // 分页信息
    pageInfo: {},
    // 数据是否加载完成
    isDataLoaded: true,
    // 是否有更多数据
    hasMore: true,
};

export const myColletionStore = create<State & Actions>()(
    immer((set, get) => ({
        ...initialState,

        /**
         * 获取我的收藏列表
         * @param pageParams 分页
         * @param isAppend 是否追加数据（用于上拉加载）
         */
        getMyColletList: async (
            pageParams: PageParams,
            isAppend = false,
        ) => {
            set((state) => {
                state.isDataLoaded = true;
            });
            try {
                Taro.showLoading({
                    title: '加载中',
                });
                const requestData = {
                    ...pageParams,
                };
                const result = await userCollectionPage(requestData);
                if (result.success) {
                    set((state) => {
                        if (isAppend) {
                            state.myColletList = [...state.myColletList, ...result?.data];
                        } else {
                            state.myColletList = result?.data;
                        }
                        state.pageInfo = {
                            pageIndex: result?.current,
                            pageSize: result?.pageSize,
                            totalCount: result?.totalCount,
                        };
                        state.hasMore = result?.pageIndex * result?.pageSize < result?.totalCount;
                    });
                }
            } catch (error) {
                console.log(error);
            } finally {
                Taro.hideLoading();
                set((state) => {
                    state.isDataLoaded = false;
                });
            }
        },

        /**
         * 上拉加载/下拉刷新
         * @param pageParams 分页
         */

        handlePullUpOrDown: async (
            pageParams: PageParams,

            isAppend = true,
        ) => {
            const newPageInfo = { ...pageParams };
            await get().getMyColletList(newPageInfo, isAppend);
        },

        /**
   * 点赞、点踩
   * @param demandId 需求id
   * @param type 操作类型，LIKE-点赞，DISLIKE-点踩
   */
        handleLikeOrDislike: async (demandId: string, type: string, status: string) => {
            try {
                const result = await operateDemand({ demandId, type, status });
                if (result.success) {
                    set((state) => {
                        const item = state.myColletList.find((d) => d.id === demandId);
                        if (item) {
                            if (type === 'LIKE') {
                                // 如果之前点踩了，先取消点踩
                                if (item.isDisliked) {
                                    item.dislikeCount = (item.dislikeCount || 0) - 1;
                                    item.isDisliked = false;
                                }
                                item.likeCount = (item.likeCount || 0) + 1;
                                item.isLiked = true;
                            } else {
                                // 如果之前点赞了，先取消点赞
                                if (item.isLiked) {
                                    item.likeCount = (item.likeCount || 0) - 1;
                                    item.isLiked = false;
                                }
                                item.dislikeCount = (item.dislikeCount || 0) + 1;
                                item.likeCount = (item.likeCount || 0) - (item.isLiked ? 1 : 0);
                                item.isLiked = false;
                                item.isDisliked = true;
                            }
                        }
                    });
                }
            } catch (error) {
                console.log(error);
            }
        },

        /**
         * 取消点赞、点踩
         * @param demandId 需求id
         * @param type 操作类型，LIKE-点赞，DISLIKE-点踩
         */
        handleCancelLikeOrDislike: async (demandId: string, type: string, status: string) => {
            console.log('handleCancelLikeOrDislike', demandId, type, status);
            try {
                const result = await cancelOperateDemand({ demandId });
                if (result.success) {
                    set((state) => {
                        const item = state.myColletList.find((d) => d.id === demandId);
                        if (item) {
                            if (type === 'LIKE') {
                                item.likeCount = (item.likeCount || 0) - 1;
                                item.isLiked = false;
                            } else {
                                item.dislikeCount = (item.dislikeCount || 0) - 1;
                                item.isDisliked = false;
                            }
                        }
                    });
                }
            } catch (error) {
                console.log(error);
            }
        },

        /**
         * 收藏
         */
        handleCollect: async (demandId: string, type: string, status: string) => {
            try {
                const result = await operateCollect({ demandId, type, status });
                if (result.success) {
                    set((state) => {
                        const item = state.myColletList.find((d) => d.id === demandId);
                        if (item) {
                            if (type === 'COLLECT' || type === 'collection') {
                                item.collectCount = (item.collectCount || 0) + 1;
                                item.collect = true;
                            }
                        }
                    });
                }
            } catch (error) {
                console.log(error);
            }
        },

        /**
         * 取消收藏
         */
        handleCancelCollect: async (demandId: string) => {
            try {
                const result = await operateCancelCollect({ demandId });
                if (result.success) {
                    set((state) => {
                        const item = state.myColletList.find((d) => d.id === demandId);
                        if (item) {
                            item.collectCount = (item.collectCount || 0) - 1;
                            item.collect = false;
                            console.log('handleCancelCollect success');
                        }
                    });
                }
            } catch (error) {
                console.log(error);
            }
        },
    })),
);
